package com.example.mymvvmdemo.net.model;

import androidx.annotation.NonNull;

import com.example.mymvvmdemo.api.API;
import com.example.mymvvmdemo.retrofit.RetrofitManager;
import com.example.mymvvmdemo.utils.LogUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

/**
 * 用来处理图片上传的请求
 */
public class ImageModel extends BaseModel {

    private IModel.ImageModel imageModel;

    public ImageModel(IModel.ImageModel imageModel) {
        this.imageModel = imageModel;
    }

    public void startLoadImage(String url, String auth_token, HashMap<String, String> params, File imageFile, String name, String type) {
        // 检查文件格式
        String fileName = imageFile.getName().toLowerCase();
        String mimeType;
        if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
            mimeType = "image/jpeg";
        } else if (fileName.endsWith(".png")) {
            mimeType = "image/png";
        } else if (fileName.endsWith(".gif")) {
            mimeType = "image/gif";
        } else {
            imageModel.loadImageFail("只支持 JPG、PNG、GIF 格式的图片", type);
            return;
        }

        // 创建图片的RequestBody
        RequestBody requestFile = RequestBody.create(MediaType.parse(mimeType), imageFile);
        // 创建MultipartBody.Part
        MultipartBody.Part body = MultipartBody.Part.createFormData(name, imageFile.getName(), requestFile);

//        // 创建其他参数的Map
//        Map<String, RequestBody> params = new HashMap<>();
//        // 如果需要添加其他参数，可以在这里添加
//        // params.put("key", RequestBody.create(MediaType.parse("text/plain"), "value"));

        // 格式化token
        String formattedToken = "Bearer " + auth_token;

        RetrofitManager.getInstance().getRetrofit().create(API.class)
                .uploadImage(url, formattedToken, body, params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        LogUtils.d("开始上传图片");
                    }

                    @Override
                    public void onNext(@NonNull ResponseBody response) {
                        try {
                            String result = response.string();
                            //判断请求网络是否异常
                            if (isNetWorkError(result)) {
                                imageModel.loadImageNetWorkError(result);
                                return;
                            }

                            JSONObject jsonObject = new JSONObject(result);
                            int code = jsonObject.getInt("code");
                            imageModel.loadImageSuccess(result, type, code);

                        } catch (Exception e) {
                            LogUtils.d("请求异常: " + e.getMessage());
                            imageModel.loadImageFail(e.getMessage(), type);
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        LogUtils.e("请求错误: " + e.getMessage());
                        LogUtils.e("错误类型: " + e.getClass().getName());

                        //判断请求网络是否异常
                        if (isNetWorkError(e.getMessage())) {
                            imageModel.loadImageNetWorkError(e.getMessage());
                            return;
                        }

                        if (e instanceof retrofit2.HttpException) {
                            retrofit2.HttpException httpException = (retrofit2.HttpException) e;
                            LogUtils.e("HTTP错误码: " + httpException.code());
                            try {
                                String errorBody = httpException.response().errorBody().string();
                                LogUtils.e("错误响应体: " + errorBody);
                            } catch (Exception ex) {
                                LogUtils.e("无法读取错误响应体: " + ex.getMessage());
                            }
                        }

                        imageModel.loadImageFail(e.getMessage(), type);
                    }

                    @Override
                    public void onComplete() {
                        LogUtils.d("图片上传完成");
                    }
                });
    }
}